package test;

public class BinarySearch {

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 7;
        int result = BinarySearch.binarySearch(array, target);
        System.out.println("The index of " + target + " is: " + result);
    }
    public static int binarySearch(int[] array, int target) {
        int left = 0;
        int right = array.length - 1;
        while (left <= right) {
            int middle = left + (right - left) / 2;
            if (target > array[middle]){
                left = middle + 1;
            }
            if (target < array[middle]){
                right = middle - 1;
            }
            if (target == array[middle]){
                return middle;
            }
        }
        return -1;
    }
}
